﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SixLottery.Helpers;
using System.Data;
using System.Collections.Specialized;

using SixLottery.Core;
using SixLottery.Common;
using SixLottery.Data;

namespace SixLottery.Models
{
    public class Member : Entity
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public int Level { get; set; }

        public Member()
        {

        }        

        public static IList<Member> GetAllMember()
        {
            string sql = "select * from member";
            Dictionary<string, object> args = new Dictionary<string,object>();
            
            DataTable dt = Access.GetInstance(Config.ConnectionString).GetDataTable(sql, args);

            EntityList<Member> memberList = new EntityList<Member>();
            memberList.Load(dt);

            return memberList;
        }

        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage CreateMember(Member member)
        {
            string connectionString = Config.ConnectionString;
            string sql = "select * from member where username = @userName";
            Dictionary<string, object> args = new Dictionary<string, object>();

            args.Add("userName", member.UserName);

            DataTable dt = Access.GetInstance(connectionString).GetDataTable(sql, args);

            bool isExists = dt.Rows.Count > 0;
            if (isExists)
            {
                return new ResultMessage() { ErrorCode = 1, Description = "用户名已经存在" };
            }                

            try
            {
                sql = "insert into  member (UserName,[Password],[Level]) values (@userName, @password, @level)";
                args.Clear();
                args.Add("userName", member.UserName);
                args.Add("password", member.Password);
                args.Add("level", (int)MemberLevelType.User);

                Access.GetInstance(connectionString).Execute(sql, args);

                return new ResultMessage() { ErrorCode = 0 };
            }
            catch (Exception ex)
            {
                return new ResultMessage() { ErrorCode = 1, Description = ex.Message };
            }
        }

        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage UpdatePassword(string old, string newp)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["darrenbo"];
            if (cookie == null)
            {
                return new ResultMessage() { ErrorCode = 1, Description = "还没有登录，无法修改。请尝试重新登录。" };
            }
            else
            {
                try
                {
                    string value = SecurityHelper.DiscuzAuthcodeDecode(cookie.Value, SecurityHelper.Key);
                    NameValueCollection nameValue = System.Web.HttpUtility.ParseQueryString(value);
                    string name = nameValue["name"];
                    string pwd = nameValue["pwd"];
                    if (pwd != old)
                    {
                        return new ResultMessage() { ErrorCode = 3, Description = "旧密码错误，请重新输入。" };
                    }
                    else
                    {
                        string sql = string.Format("update [member] set [password]='{0}' where UserName='{1}'", newp, name);
                        AccessHelper.ExecuteScalar(Config.ConnectionString, sql);
                        return new ResultMessage() { ErrorCode = 0, Description = "修改成功，请重新登录" };
                    }
                }
                catch (Exception)
                {
                    return new ResultMessage() { ErrorCode = 2, Description = "解析当前用户数据失败。请尝试重新登录。" };

                }
            }
        }
        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Login(string name, string pwd)
        {
            name = name.Replace("'", "");
            pwd = pwd.Replace("'", "");

            string connectionString = Config.ConnectionString;
            
            string sql = "select [level] from [member] where username=@userName and password=@password";
            Dictionary<string, object> args = new Dictionary<string, object>();

            args.Add("userName", name);
            args.Add("password", pwd);

            int level = Access.GetInstance(connectionString).ExecuteScaler<int>(sql, args);

            if (level > 0)
            {
                string cookieValue = string.Format("name={0}&pwd={1}&level={2}", name, pwd, level);
                HttpContext.Current.Session["name"] = cookieValue;
                cookieValue = SecurityHelper.DiscuzAuthcodeEncode(cookieValue, SecurityHelper.Key);

                HttpCookie cookie = new HttpCookie("darrenbo", cookieValue);
                HttpContext.Current.Response.Cookies.Add(cookie);

                return new ResultMessage() { ErrorCode = 0, Description = "seccess" };
            }
            else
            {
                
                return new ResultMessage() { ErrorCode = 1, Description = "用户名或密码错误！" };
            }

        }


        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = false)]
        public static ResultMessage GetPaging(int pagesize, int pageNum)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request["pagesize"] != null)
                pagesize = int.Parse(request["pagesize"]);
            if (request["pagenum"] != null)
                pageNum = int.Parse(request["pagenum"]);

            var memberList = GetAllMember();
            var ps = memberList.Select(m => new { UserName = m.UserName, Password = m.Password}).Skip((pageNum - 1) * pagesize).Take(pagesize);

            var data = new { total = memberList.Count, rows = ps };
            return new ResultMessage() { ErrorCode = 0, Name = "success", Value = data };
        }


        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Delete(string username)
        {            
            string sql = "delete from member where username = @userName";

            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("@userName", username);

            Access.GetInstance(Config.ConnectionString).Execute(sql, args);
            
            return new ResultMessage() { ErrorCode = 0 };
        }

        [DarrenAjax.Utility.jQueryInvokeMethod(Url = "handlers/AjaxController.ashx", Method = "post", DataType = "json", Async = true)]
        public static ResultMessage Update(Member member)
        {
            string connectionString = Config.ConnectionString;
            string sql = "update [Member] set [Password]=@password where [UserName]=@userName";

            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("password", member.Password);
            args.Add("userName", member.UserName);
            args.Add("level", (int)MemberLevelType.User);

            Access.GetInstance(Config.ConnectionString).Execute(sql, args);
            
            return new ResultMessage() { ErrorCode = 0 };
        }
    }
}